package com.zl.sqlmerge.service;


import com.zl.sqlmerge.entity.request;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.*;

/**
 * @author wuze
 */
@Service
@Slf4j
public class testService {

    public volatile int count = 0;
    public volatile int sum = 0;

    Queue<request> queue = new LinkedBlockingQueue<>();
//    Queue<request> queue = new ArrayBlockingQueue<>(10000);

    public String test01(String id) throws ExecutionException, InterruptedException {
        CompletableFuture<String> completableFuture = new CompletableFuture<>();
        String uuid = UUID.randomUUID().toString();
        request request = new request(id,uuid,completableFuture);
        queue.add(request);
        return completableFuture.get();
    }

    @PostConstruct
    public void doSQL(){
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        scheduledExecutorService.scheduleAtFixedRate(()->{
            int size = queue.size();
            if(size == 0){
                return;
            }
            count++;
            sum+= size;
            log.info("第{}次:{}--当前处理总数:{}",count,size,sum);
            //封装参数list
            List<Map<String,String>> params = new ArrayList<>();
            //封装回调request
            List<request> requests = new ArrayList<>();
            for(int i = 0; i<size; i++){
                request request = queue.poll();
                Map<String,String> map = new HashMap<>();
                map.put("id", request.getId());
                map.put("uuid", request.getUuid());
                params.add(map);
                requests.add(request);
            }
            //模拟调用远程list接口，同步等待
            List<Map<String, String>> responses = getresponse(params);
            for (Map<String, String> response : responses) {
                String uuid = response.get("uuid");
                String res = response.get("response");
                for (request request : requests) {
                    if(request.getUuid().equals(uuid)){
                        request.getFuture().complete(res);
                    }
                }
            }
        },100,20, TimeUnit.MILLISECONDS);
    }

    public List<Map<String,String>> getresponse(List<Map<String,String>> params){

        List<Map<String,String>> response = new ArrayList<>();
        for (Map<String, String> param : params) {
            String uuid = param.get("uuid");
            String id = param.get("id");
            Map<String,String> map = new HashMap<>();
            map.put("response",id+"结果");
            map.put("uuid", uuid);
            response.add(map);
        }

        return response;
    }
}
